package com.ityls.springsecuritystudy.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ityls.springsecuritystudy.domain.Permission;
import com.ityls.springsecuritystudy.domain.Users;
import com.ityls.springsecuritystudy.mapper.UsersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    private UsersMapper usersMapper;

    // 自定义认证逻辑
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1.构造查询条件
        QueryWrapper<Users> wrapper = new QueryWrapper<Users>().eq("username", username);
        // 2.查询用户
        Users users = usersMapper.selectOne(wrapper);
        if (users == null){
            return null;
        }
        // 3.查询用户权限
        List<Permission> permissions = usersMapper.findPermissionByUserName(username);
        // 4.将自定义权限集合转为Security的权限类型集合
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        for (Permission permission : permissions) {
            grantedAuthorities.add(new SimpleGrantedAuthority(permission.getUrl()));
        }

        // 3.封装为UserDetails对象
        UserDetails userDetails = User
                .withUsername(users.getUsername())
                .password(users.getPassword())
                .authorities(grantedAuthorities)
                .build();
        // 4.返回封装好的UserDetails对象
        return userDetails;
    }
}

